package com.yellowpage.alarm.service;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.yellowpage.alarm.data.AlarmInfoUser;
import com.yellowpage.ca.dao.UserDao;
import com.yellowpage.ca.data.User;
import com.yellowpage.mail.bean.MailBean;
import com.yellowpage.mail.service.MailSendService;
import com.yellowpage.white.exception.AlarmException;
import com.yellowpage.white.exception.MailSendException;

/**
 * 告警信息邮件通知业务接口实现类
 * 
 * @author leasass
 * 
 */
public class AlarmInfoNotifyByEmailServiceImpl implements
		AlarmInfoNotifyService {
	private final Log log = LogFactory.getLog(getClass());

	/**
	 * 用户DAO接口
	 */
	private UserDao userDao;

	/**
	 * 邮件发送业务接口
	 */
	private MailSendService mailSendService;
	/**
	 * 邮件主题
	 */
	private String subject;

	public String getSubject() {
		return subject;
	}

	public void setSubject(String subject) {
		this.subject = subject;
	}

	public MailSendService getMailSendService() {
		return mailSendService;
	}

	public void setMailSendService(MailSendService mailSendService) {
		this.mailSendService = mailSendService;
	}

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}

	@Override
	public void notify(String cause, List<AlarmInfoUser> alarmInfoUsers)
			throws AlarmException {
		// 邮件接收人
		StringBuffer emailBuf = new StringBuffer();

		for (AlarmInfoUser alarmInfoUser : alarmInfoUsers) {
			Long userId = alarmInfoUser.getUserId();

			User user = this.getUserDao().get(userId);

			if (null != user) {
				emailBuf.append(user.getEmail() + ";");
			}
		}

		MailBean mail = new MailBean();
		// 邮件标题
		mail.setSubject(this.subject);
		// 邮件内容
		mail.setMessage(cause);
		// 邮件接收人
		mail.setTo(emailBuf.toString());

		try {
			this.mailSendService.sendMail(mail);
		} catch (MailSendException e) {
			log.error(e.getMessage(), e);
			throw new AlarmException("告警信息邮件通知失败,失败原因为["+e.getMessage()+"]", e);
		}

	}

}
